<template>
  <div class="update-photo">
    <img :src="img" ref="imgRef"/>
    <div class="toolbar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">确定</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { upDateUSerPhoto } from '@/api/user'
export default {
  name: 'UpdatePhoto',
  components: {

  },
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  data () {
    return {
      cropper: null
    }
  },
  created () {

  },
  mounted () {
    const image = this.$refs.imgRef
    this.cropper = new Cropper(image, {
      viewMode: 1, // 限制裁切框不要超过画布的大小。
      dragMode: 'move', // 定义裁纸器的拖动模式。
      aspectRatio: 1, // 定义裁剪框的固定长宽比。默认情况下，裁剪框为自由比例。
      autoCropArea: 1, // 0到1之间的数字。定义自动裁剪区域的大小（百分比）。
      cropBoxMovable: false, // 启用通过拖动来移动裁剪框的功能。
      cropBoxResizable: false, // 启用以通过拖动来调整裁剪框的大小。
      background: false
    })
  },
  methods: {
    onConfirm () {
      this.cropper.getCroppedCanvas().toBlob(async (blob) => {
        const formData = new FormData()
        formData.append('photo', blob)
        const { data } = await upDateUSerPhoto(formData)
        this.$emit('update-photo', data.data.photo)
        this.$emit('close')
        console.log(data)
      })
    }
  }
}
</script>

<style lang="less" scoped>
img {
  max-width: 100%;
  display: block;
}
.update-photo {
  background-color: #000;
  height: 100%;
}
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: space-between;
  .cancel,
  .confirm {
    width: 90px;
    height: 90px;
    font-size: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
  }
}
</style>
